package com.yuyang.wifi.views;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.utils.DeviceUtil;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.List;

/**
 * created by mej
 * on 2020/12/2
 */
public class LoadCsjMsgUtils {

    private Context mContext;
    private TTAdManager mTTMang;
    private TTNativeExpressAd mTTAd;
    private TTAdNative mTTAdNative;
    private int minSplashTimeWhenNoAD = 1000;
    private FrameLayout mExpressContainer;
    private OnItemAllClickListener onItemAllClickListener;
    private int mWidth, mHeight;
    /**
     * 记录拉取广告的时间
     */
    private long fetchSplashADTime = 0;
    static LoadCsjMsgUtils instance = new LoadCsjMsgUtils();
    private String mCsjMsgAdID;

    private OnLoadFailureListener onLoadFailureListener;

    public static LoadCsjMsgUtils getInstance() {
        return instance;
    }

    //一、加载穿山甲激励视频
    //BDAdvanceBaseAppNative 绑定激励视频回调
    public void load(final Context context, FrameLayout frameLayout, int width, int height, String moduleName) {
        mContext = context;
        mWidth = width;
        mHeight = height;
        mExpressContainer = frameLayout;
//        if (!TextUtils.isEmpty(csjMsgAdId)) {
//            mCsjMsgAdID = csjMsgAdId;
//        } else {
//            mCsjMsgAdID = "945989403";
//        }
        mCsjMsgAdID = MyApplication.getCsjAdIdChannel(moduleName);
//        String  streamStatus = SpUtil.find(AppConstant.KEY_STREAM_STATUS);
//        if(streamStatus!=null&&!streamStatus.isEmpty()&&streamStatus.equals("0")) {
        initCsjMsgAdAppId();
//        }
    }

    private void initCsjMsgAdAppId() {
        if (mTTMang == null) {
            mTTMang = TTAdSdk.getAdManager();
            // mTTMang.requestPermissionIfNecessary(mContext.getApplicationContext());
        }
        if (mTTAd == null) {
            if (null != mContext) {
                mTTAdNative = mTTMang.createAdNative(mContext.getApplicationContext());
            }
        }
        initCsjMsgAdView();
    }

    private void initCsjMsgAdView() {
        int screenWidth = DeviceUtil.getWidth(mContext);
        //设置广告参数
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mCsjMsgAdID) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(mWidth, mHeight) //必填：期望个性化模板广告view的size,单位dp
                //.setImageAcceptedSize(300, 300) //这个参数设置即可，不影响个性化模板广告的size
                .build();
        //加载广告
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e("csj_msg", "onError:======" + message);
                //mExpressContainer.removeAllViews();
                //initAdView();
                /**
                 * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
                 * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
                 * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
                 **/
                long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
                if (alreadyDelayMills > minSplashTimeWhenNoAD) {
                    mExpressContainer.removeAllViews();
//                    mExpressContainer.setVisibility(View.GONE);
                } else {
                    mExpressContainer.removeAllViews();
                    initCsjMsgAdView();
                }

                if (null != onLoadFailureListener) {
                    onLoadFailureListener.onLoadFailureListener();
                }
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                } else {
                    mTTAd = ads.get(0);
                    bindAdListener(mTTAd);
                    mTTAd.render();//调用render开始渲染广告
                }
            }
        });
    }

    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int i) {

            }

            @Override
            public void onAdShow(View view, int i) {

            }

            @Override
            public void onRenderFail(View view, String s, int i) {
                Log.e("csj_msg", "onError:ss======" + s);
                long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
                if (alreadyDelayMills > minSplashTimeWhenNoAD) {
                    //mExpressContainer.setVisibility(View.GONE);
                    mExpressContainer.removeAllViews();
                } else {
                    mExpressContainer.removeAllViews();
                    initCsjMsgAdView();
                }
            }

            @Override
            public void onRenderSuccess(View view, float v, float v1) {
                try {
                    if (null != mExpressContainer) {
//                        int visibility = mExpressContainer.getVisibility();
//                        if (visibility != 0) {
//                            mExpressContainer.setVisibility(View.VISIBLE);
//                            mExpressContainer.removeAllViews();
//                            mExpressContainer.addView(view);
//                            if (null != onItemAllClickListener) {
//                                onItemAllClickListener.onItemAllClickListener();
//                            }
//                        }
                        mExpressContainer.setVisibility(View.VISIBLE);
                        mExpressContainer.removeAllViews();
                        mExpressContainer.addView(view);
                        if (null != onItemAllClickListener) {
                            onItemAllClickListener.onItemAllClickListener();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //dislike设置
        bindDislike(ad, false);
    }

    /**
     * 设置广告的不喜欢，注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
     *
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
        //使用默认模板中默认dislike弹出样式
        ad.setDislikeCallback((Activity) mContext, new TTAdDislike.DislikeInteractionCallback() {


            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onCancel() {
                // ToastUtils.showShortToast(mContext, "点击取消 ");
            }

        });
    }


    public void destroyView() {
        if (mTTAd != null) {
            mTTAd.destroy();
        }
    }

    public interface OnItemAllClickListener {
        void onItemAllClickListener();
    }

    public void setItemAllClickListener(OnItemAllClickListener onItemAllClickListener) {
        this.onItemAllClickListener = onItemAllClickListener;
    }


    public interface OnLoadFailureListener {
        void onLoadFailureListener();
    }

    public void setLoadFailureListener(OnLoadFailureListener onLoadFailureListener) {
        this.onLoadFailureListener = onLoadFailureListener;
    }

}
